package org.hbgl.geoentity.admin.web.admin;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hbgl.geoentity.admin.annotation.OperationLog;
import org.hbgl.geoentity.admin.annotation.RequiresPermissionsDesc;
import org.hbgl.geoentity.admin.aspect.OperationType;
import org.hbgl.geoentity.admin.shiro.UserType;
import org.hbgl.geoentity.admin.web.BaseController;
import org.hbgl.geoentity.core.util.JacksonUtil;
import org.hbgl.geoentity.core.util.ResponseUtil;
import org.hbgl.geoentity.db.domain.GeColumn;
import org.hbgl.geoentity.db.domain.GeUser;
import org.hbgl.geoentity.db.util.EnumFile;
import org.hbgl.geoentity.db.vo.ColumnBoxVo;
import org.hbgl.geoentity.db.vo.ColumnVo;
import org.hbgl.geoentity.db.vo.ContentVo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

import static org.hbgl.geoentity.admin.util.ResponseCode.*;
import static org.hbgl.geoentity.admin.util.ResponseCode.ADMIN_COLUMN_HAVE_CONTENT;

/**
 * 代码功能：栏目管理
 * 开发日期：2022/4/26
 * 作者：蒋海仑
 * 联系方式：
 * 版本更迭说明：
 * 版权信息：河北广联信息技术有限公司
 */
@RestController
@RequestMapping("/admin/column")
@Validated
public class AdminColumnController extends BaseController {

    /**
     * 获取栏目列表
     */
    @RequiresPermissions("admin:column:list")
    @RequiresPermissionsDesc(menu = {"站点管理", "栏目管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(@RequestParam(defaultValue = "") String keywords,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit) {
        GeUser userCurrent = getCurrentAdminUser();
        List<ColumnVo> columnVos = columnService.selectColumnList(keywords, page, limit);
        return ResponseUtil.okList(columnVos);
    }

    /**
     * 添加栏目
     */
    @RequiresPermissions("admin:column:create")
    @RequiresPermissionsDesc(menu = {"站点管理", "栏目管理"}, button = "添加栏目")
    @OperationLog(detail = "新建栏目", operationType = OperationType.INSERT, userType = UserType.ADMIN)
    @PostMapping("/create")
    public Object create(@RequestBody GeColumn column) {
        Integer parentId = column.getParentId();
        String columnName = column.getName();
        if (!ObjectUtils.allNotNull(
                parentId, columnName
        )) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isBlank(columnName)) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        List<GeColumn> columnList = columnService.findByColumnName(parentId, columnName);
        if (columnList != null && columnList.size() > 0) {
            return ResponseUtil.fail(ADMIN_NAME_EXIST, "栏目已经存在");
        }
        columnService.insertColumn(column);
        return ResponseUtil.ok();
    }

    /**
     * 根据栏目ID查询栏目信息
     *
     * @param id 栏目ID
     */
    @RequiresPermissions("admin:column:detail")
    @RequiresPermissionsDesc(menu = {"站点管理", "栏目管理"}, button = "详情")
    @OperationLog(detail = "查看栏目详情", operationType = OperationType.SELECT, userType = UserType.ADMIN)
    @GetMapping("/detail")
    public Object detail(@NotNull Integer id) {
        GeUser userCurrent = getCurrentAdminUser();

        ColumnVo columnVo = columnService.findColumnById(id);
        if (columnVo == null) {
            return ResponseUtil.badArgumentValue();
        }

        return ResponseUtil.ok(columnVo);
    }

    /**
     * 删除栏目
     *
     * @param id 部门信息
     */
    @RequiresPermissions("admin:column:delete")
    @RequiresPermissionsDesc(menu = {"站点管理", "栏目管理"}, button = "删除")
    @OperationLog(detail = "删除栏目", operationType = OperationType.DELETE, userType = UserType.ADMIN)
    @GetMapping("/delete")
    public Object delete(@NotNull Integer id) {
        GeUser userCurrent = getCurrentAdminUser();
        //判断该栏目下是否有文章
        List<ContentVo> contentVos = contentService.selectSiteContentList(id, null, null, null);
        if(contentVos != null && contentVos.size()>0) {
            return ResponseUtil.fail(ADMIN_COLUMN_HAVE_CONTENT, "请先删除该栏目下的内容再删除此栏目");
        }
        //判断该栏目是否有子栏目
        List<GeColumn> geColumns = columnService.selectColumnByParentId(id);
        if(geColumns != null && geColumns.size()>0) {
            return ResponseUtil.fail(ADMIN_COLUMN_HAVE_CHILD, "请先删除该栏目下的子栏目再删除此栏目");
        }
        columnService.deleteColumnById(id);
        return ResponseUtil.ok();
    }

    /**
     * 编辑栏目信息
     *
     * @param column 栏目信息
     */
    @RequiresPermissions("admin:column:update")
    @RequiresPermissionsDesc(menu = {"站点管理", "栏目管理"}, button = "编辑")
    @OperationLog(detail = "编辑栏目信息", operationType = OperationType.UPDATE, userType = UserType.ADMIN)
    @PostMapping("/update")
    public Object update(@RequestBody GeColumn column) {
        Integer id = column.getId();
        Integer parentId = column.getParentId();
        String name = column.getName();
        if (!ObjectUtils.allNotNull(
                id, parentId, name
        )) {
            return ResponseUtil.badArgument();
        }
        if (parentId.equals(id)) {
            return ResponseUtil.badArgumentValue();
        }
        if (StringUtils.isBlank(name)) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        ColumnVo columnVo = columnService.findColumnById(id);
        if (columnVo == null) {
            return ResponseUtil.badArgumentValue();
        }
        List<GeColumn> byColumnName = columnService.findByColumnName(parentId, name);
        if (byColumnName != null && byColumnName.size()>0 && !byColumnName.get(0).getId().equals(id)) {
            return ResponseUtil.fail(DEPARTMENT_NAME_EXIST, "栏目已经存在");
        }

        if (columnService.updateColumn(column) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    /**
     * 启用/禁用栏目
     *
     * @param body { id : 栏目ID, state : 状态 }
     */
    @RequiresPermissions("admin:column:state")
    @RequiresPermissionsDesc(menu = {"站点管理", "栏目管理"}, button = "启用/禁用")
    @OperationLog(detail = "启用/禁用栏目", operationType = OperationType.UPDATE, userType = UserType.ADMIN)
    @PostMapping("/state")
    public Object state(@RequestBody String body) {
        Integer id = JacksonUtil.parseInteger(body, "id");
        Integer state = JacksonUtil.parseInteger(body, "state");
        if (!ObjectUtils.allNotNull(
                id, state
        )) {
            return ResponseUtil.badArgument();
        }
        if (state != EnumFile.CommonState.Normal && state != EnumFile.CommonState.Disable) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        if (state == EnumFile.CommonState.Disable) {
            // 如果当前角色所对应管理员仍存在，则拒绝删除角色。
            List<GeColumn> childColum = columnService.selectColumnByParentId(id);
            childColum = childColum.stream().filter(p->p.getState().equals(EnumFile.CommonState.Normal)).collect(Collectors.toList());

            if (childColum != null && childColum.size()>0) {
                return ResponseUtil.fail(DEPARTMENT_USER_EXIST, "当前栏目存在启用的子栏目，不能禁用");
            }

        }

        ColumnVo columnVo = columnService.findColumnById(id);
        if (columnVo == null) {
            return ResponseUtil.badArgumentValue();
        }
        GeColumn geColumn = new GeColumn();
        geColumn.setId(id);
        geColumn.setState(state);

        if (columnService.updateColumn(geColumn) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    /**
     * 通过父级栏目获取子栏目列表
     * 顶级栏目 parentId为0
     */
    // @RequiresPermissions("admin:column:parentcolumnlist")
    // @RequiresPermissionsDesc(menu = {"站点管理", "栏目管理"}, button = "查询子栏目")
    @GetMapping("/parentColumnList")
    public Object parentColumnList(@RequestParam(defaultValue = "0") Integer parentId) {
        GeUser userCurrent = getCurrentAdminUser();
        List<GeColumn> columnChildList = columnService.selectColumnByParentId(parentId);
        columnChildList = columnChildList.stream().filter(p->p.getState().equals(EnumFile.CommonState.Normal)).collect(Collectors.toList());
        return ResponseUtil.ok(columnChildList);
    }

}
